package cookie.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "LastAccessServlet", urlPatterns = "/LastAccessServlet")

public class LastAccessServlet extends HttpServlet {
    private static final long serialVersionUID=1L;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String lastAccessTime = null;
        //获取所有的cookie，并将这些cookie存放在数组中
        Cookie[] cookies= request.getCookies();
        //遍历cookie数组
        for(int i=0;cookies!=null && i< cookies.length;i++){
            if("lastAccess".equals(cookies[i].getName())){
                lastAccessTime=cookies[i].getValue();
                break;
            }
        }
        //判断是否存在名称为lastAccess的cookie
        if(lastAccessTime == null){
            response.getWriter().print("您是首次访问本站！！！");
        }else {
            response.getWriter().print("您上次的访问时间是："+lastAccessTime);
        }
        //创建cookie，将当前时间作为cookie的值发送给客户端
        String currentTime=new SimpleDateFormat("yyyy-M-d:hh:mm:ss").format(new Date());
        Cookie cookie = new Cookie("lastAccess",currentTime);
        //发送cookie
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
